/*
 * @Author: xfworld
 * @Date: 2019-08-09 09:45:16
 * @LastEditors: xfworld
 * @LastEditTime: 2020-05-28 15:37:27
 * @Description:
 */
import axios from "axios";
import store from "@/store";
import router from "@/router";
import Vue from "vue";

class HttpRequest {
  constructor(baseUrl = baseURL) {
    this.baseUrl = baseUrl;
    this.queue = {};
  }
  getInsideConfig() {
    const config = {
      baseURL: this.baseUrl,
      headers: {
        //
      }
    };
    return config;
  }
  destroy(url) {
    delete this.queue[url];
    if (!Object.keys(this.queue).length) {
      //  Spin.hide()
    }
  }
  interceptors(instance, url) {
    // 请求拦截
    instance.interceptors.request.use(
      config => {
        // 增加头部认证数据
        if (store.getters.token !== null && store.getters.token !== undefined && store.getters.token !== "") {
          Object.assign(config.headers, {
            Authorization: store.getters.token
          });
        }

        // 添加全局的loading...
        if (!Object.keys(this.queue).length) {
          //  Spin.show() // 不建议开启，因为界面不友好
        }
        this.queue[url] = true;
        return config;
      },
      error => {
        return Promise.reject(error);
      }
    );
    // 响应拦截
    instance.interceptors.response.use(
      res => {
        this.destroy(url);
        if (!res.data) {
          return Promise.reject(res);
        }
        const {data, status} = res;
        return {data, status};
      },
      error => {
        this.destroy(url);
        if (error && error.response) {
          switch (error.response.status) {
            case 400:
              error.message = "请求错误(400)";
              break;
            case 401:
              error.message = "未授权，请重新登录(401)";
              // 401 清除token信息并跳转到登录页面
              if (error.response.data != null) {
                let code = error.response.data.code;
                if (code >= 700) {
                  //Vue.prototype.$toast.fail("需要登录");
                  Vue.prototype.$dialog
                    .alert({
                      title: "授权过期",
                      message: "请重新登录!"
                    })
                    .then(() => {
                      // on close
                      store.dispatch("setSignOut");
                      router.replace({
                        path: "/login",
                        query: {
                          redirect: router.currentRoute.fullPath
                        }
                      });
                    });
                }
              }
              break;
            case 403:
              error.message = "拒绝访问(403)";
              break;
            case 404:
              error.message = "请求出错(404)";
              break;
            case 408:
              error.message = "请求超时(408)";
              break;
            case 500:
              error.message = "服务器错误(500)";
              break;
            case 501:
              error.message = "服务未实现(501)";
              break;
            case 502:
              error.message = "网络错误(502)";
              break;
            case 503:
              error.message = "服务不可用(503)";
              break;
            case 504:
              error.message = "网络超时(504)";
              break;
            case 505:
              error.message = "HTTP版本不受支持(505)";
              break;
            default:
              error.message = `连接出错(${error.response.status})!`;
          }
        } else {
          error.message = "连接服务器失败!";
        }
        // let errorInfo = error.response
        // if (!errorInfo) {
        //     const {
        //         request: {
        //             statusText,
        //             status
        //         },
        //         config
        //     } = JSON.parse(JSON.stringify(error))
        //     errorInfo = {
        //         statusText,
        //         status,
        //         request: {
        //             responseURL: config.url
        //         }
        //     }
        // }
        // addErrorLog(errorInfo)
        return Promise.reject(error);
      }
    );
  }
  // 增加验证项
  request(options) {
    const instance = axios.create({
      withCredentials: true
    });
    options = Object.assign(this.getInsideConfig(), options);
    this.interceptors(instance, options.url);

    return instance(options);
  }
}
export default HttpRequest;
